Imports Cdm.DataCore.CaseNotes
Imports System.Collections.Generic
Imports Cdm.DataCore.LookupTables

Partial Class Admin_StatusChangeReason
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindStatusDropDown()
            BindGrid()
        End If
        ClearStatus()
        SetupJavaScript()
    End Sub

    Private Sub BindStatusDropDown()
        Me.StatusDropdown.DataSource = LuCaseStatus.ListBySort("Description")
        StatusDropdown.DataTextField = "Description"
        StatusDropdown.DataValueField = "CaseStatusId"
        Me.StatusDropdown.DataBind()
        Me.StatusDropdown.Items.Insert(0, New ListItem("All", "0"))
    End Sub

    Private Sub BindGrid()
        Me.StatusReasonScrollingGridView.DataSource = GetDataSource()
        Me.StatusReasonScrollingGridView.DataBind()
    End Sub

    Private Function GetDataSource() As List(Of CaseStatusReason)
        Dim statusId As Integer = CInt(Me.StatusDropdown.SelectedValue)
        Return CaseStatusReason.ListByCaseStatus(statusId, False)
    End Function

    Protected Sub SubmitStatusButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitStatusButton.Click
        BindGrid()
    End Sub

    Protected Sub StatusReasonScrollingGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles StatusReasonScrollingGridView.RowCancelingEdit
        Try
            StatusReasonScrollingGridView.EditIndex = -1
            BindGrid()
            SetStatus("Edit has been cancelled.")
        Catch ex As System.Exception
            SetStatus("Error Cancelling Edit: " & ex.Message)
        End Try
    End Sub

    Protected Sub StatusReasonScrollingGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles StatusReasonScrollingGridView.RowDataBound
        Dim deleteButton As Button = CType(e.Row.FindControl("DeleteButton"), Button)
        If Not deleteButton Is Nothing Then
            deleteButton.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this status reason?');")
        End If
    End Sub

    Protected Sub StatusReasonScrollingGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles StatusReasonScrollingGridView.RowEditing
        StatusReasonScrollingGridView.EditIndex = e.NewEditIndex
        BindGrid()
    End Sub

    Protected Sub StatusReasonScrollingGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles StatusReasonScrollingGridView.RowUpdating
        Try
            Dim id = CInt(StatusReasonScrollingGridView.DataKeys(e.RowIndex)(0))
            Dim updatedReason As Cdm.DataCore.CaseNotes.CaseStatusReason = Cdm.DataCore.CaseNotes.CaseStatusReason.Retrieve(id)
            Dim editTextBox As TextBox = StatusReasonScrollingGridView.Rows(e.RowIndex).FindControl("EditDescriptionTextBox")


            If Not editTextBox Is Nothing Then
                updatedReason.Description = editTextBox.Text
                If editTextBox.Text.Trim() = "" Then
                    SetStatus("Can not update.  Please enter a value for status reason.")
                    Exit Sub
                ElseIf ReasonExistsForStatus(editTextBox.Text, id) Then
                    SetStatus("Can not update.  This reason already exists for this status, or all statuses.")
                End If
            End If

            updatedReason.Persist()

            StatusReasonScrollingGridView.EditIndex = -1
            BindGrid()
        Catch ex As Exception
            SetStatus("Error Updating Status Reason: " + ex.Message)
        End Try
    End Sub

    Protected Sub AddReasonButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AddReasonButton.Click
        Try

            If AddReasonTextBox.Text = "" Then Exit Sub

            If ReasonExistsForStatus(Me.AddReasonTextBox.Text, 0) Then
                SetStatus("Can not add.  This reason already exists for this status, or all statuses.")
                Exit Sub
            End If

            Dim addReason As New Cdm.DataCore.CaseNotes.CaseStatusReason()
            addReason.CaseStatusId = CInt(Me.StatusDropdown.SelectedValue)
            addReason.Description = Me.AddReasonTextBox.Text()
            addReason.Persist()

            AddReasonTextBox.Text = ""
            BindGrid()
            SetStatus("New Reason added.")
        Catch ex As Exception
            SetStatus("Error Adding Reason: " + ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' When adding or editing a reason, make sure that
    ''' the reason text does not already exist for this status
    ''' </summary>
    ''' <param name="reasonText"></param>
    ''' <param name="currentReasonId"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ReasonExistsForStatus(ByVal reasonText As String, ByVal currentReasonId As Integer) As Boolean
        Dim reasonList As List(Of CaseStatusReason) = CaseStatusReason.ListByCaseStatus(CInt(StatusDropdown.SelectedValue), True)

        'If no items - immediately return false
        If reasonList Is Nothing Then Return False
        If reasonList.Count = 0 Then Return False

        For i As Integer = 0 To reasonList.Count - 1
            If reasonList(i).Description.ToLower().Equals(reasonText.ToLower()) And _
                   reasonList(i).CaseStatusReasonId <> currentReasonId Then
                Return True
            End If
        Next

        Return False
    End Function

    Protected Sub DeleteReasonButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            Dim deleteButton As Button = CType(sender, Button)
            Dim reasonId As Integer = CInt(deleteButton.CommandArgument)
            Dim deleteReason As Cdm.DataCore.CaseNotes.CaseStatusReason = Cdm.DataCore.CaseNotes.CaseStatusReason.Retrieve(reasonId)
            deleteReason.Remove()
            BindGrid()
            SetStatus("Reason has been deleted.")

        Catch exGentle As Gentle.Common.GentleException
            If Not exGentle.InnerException Is Nothing Then
                If exGentle.InnerException.Message.ToLower().Contains("conflict") Then
                    SetStatus("Can not delete this reason; it has been used for a participant already.")
                Else
                    SetStatus("Error deleting reason: " + exGentle.Message)
                End If
            Else
                SetStatus("Error deleting reason: " + exGentle.Message)
            End If
        Catch ex As Exception
            SetStatus("Error deleting reason: " + ex.Message)
        End Try
    End Sub


    Private Sub SetupJavaScript()

        EntityController.JavaScriptAddChildDiv(Me.StatusReasonScrollingGridView.DivClientId, CInt(Me.StatusReasonScrollingGridView.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs", EntityController.JavaScriptScrollingGridStartup(Me.StatusReasonScrollingGridView), True)
        EntityController.JavaScriptSetFixedHeight(40)
    End Sub

    Private Sub ClearStatus()
        SetStatus("")
    End Sub
    Private Sub SetStatus(ByVal message As String)
        Dim mymaster As ASP.admin_admin_master = CType(Me.Master, ASP.admin_admin_master)
        mymaster.SetStatus(message)
    End Sub

End Class
